#include "UserManagerMenu.h"
#include "LogManagerMenu.h"
#include "ui_UserManagerMenu.h"
#include "User.h"
#include "PermissionBitsChoseMenu.h"

UserManagerMenu::UserManagerMenu(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::UserManagerMenu)
{
    UserManagerMenu::initMenu();
}

UserManagerMenu::UserManagerMenu(User userInfo, QWidget *parent)
    :QWidget(parent),ui(new Ui::UserManagerMenu),
    m_userInfo(userInfo)
{
    UserManagerMenu::initMenu();
}

UserManagerMenu::~UserManagerMenu()
{
    delete ui;
}

void UserManagerMenu::initMenu()
{
    ui->setupUi(this);

    ui->le_permissionBits->setStatusTip("权限位");
    ui->btn_add->setStatusTip("添加的用户id不可以重复");
    ui->btn_delete->setStatusTip("删除用户之前请先选择一条数据");
    ui->btn_update->setStatusTip("选中数据之后点击除了编辑框之外的内容都会退出选中状态");
    ui->btn_find->setStatusTip("按照姓名模糊查询");
    ui->le_find->setStatusTip("请输入要查找用户的姓名");
    ui->btn_refresh->setStatusTip("刷新用户数据列表");

    m_sqlQueryModel = new QSqlQueryModel;
    m_sqlQueryModel->setQuery("SELECT * FROM user");

    m_sqlQueryModel->setHeaderData(0,Qt::Horizontal,tr("ID"));
    m_sqlQueryModel->setHeaderData(1,Qt::Horizontal,tr("姓名"));
    m_sqlQueryModel->setHeaderData(2,Qt::Horizontal,tr("密码"));
    m_sqlQueryModel->setHeaderData(3,Qt::Horizontal,tr("权限位"));
    m_sqlQueryModel->setHeaderData(4,Qt::Horizontal,tr("角色"));
    m_sqlQueryModel->setHeaderData(5,Qt::Horizontal,tr("用户角色描述"));

    ui->tv_userInfoList->setSelectionBehavior(QAbstractItemView::SelectRows); // 单击选中整行
    ui->tv_userInfoList->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//宽度自动伸展
    ui->tv_userInfoList->verticalHeader()->setVisible(false);//不显示行号

    ui->tv_userInfoList->setModel(m_sqlQueryModel);

    connect(ui->tv_userInfoList,&QTableView::clicked,this,&UserManagerMenu::m_on_tv_userInfoList_clicked);
    connect(ui->btn_add,&QPushButton::clicked,this,&UserManagerMenu::m_on_btn_add_clicked);
    connect(ui->btn_delete,&QPushButton::clicked,this,&UserManagerMenu::m_on_btn_delete_clicked);
    connect(ui->btn_update,&QPushButton::clicked,this,&UserManagerMenu::m_on_btn_update_clicked);
    connect(ui->btn_find,&QPushButton::clicked,this,&UserManagerMenu::m_on_btn_find_clicked);
    connect(ui->btn_refresh,&QPushButton::clicked,this,[this](){m_tv_userInfoListSelectflag=false;m_sqlQueryModel->setQuery("SELECT * FROM user");});
    connect(ui->tbtn_permissionBitsChose,&QToolButton::clicked,this,&UserManagerMenu::m_on_tbtn_permissionBitsChose_clicked);

    connect(ui->rbtn_roleAdmin,&QRadioButton::clicked,this,[this](){ui->le_role->setText(reRoleMap[Role::ADMIN]);});
    connect(ui->rbtn_roleUserInfo,&QRadioButton::clicked,this,[this](){ui->le_role->setText(reRoleMap[Role::USER_INFO]);});
    connect(ui->rbtn_roleUserStoreIO,&QRadioButton::clicked,this,[this](){ui->le_role->setText(reRoleMap[Role::USER_STORE_IO]);});
    connect(ui->rbtn_roleUserStoreCheck,&QRadioButton::clicked,this,[this](){ui->le_role->setText(reRoleMap[Role::USER_STORE_CHECK]);});
}


void UserManagerMenu::mouseReleaseEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        m_tv_userInfoListSelectflag = false;

        ui->le_id->clear();
        ui->le_name->clear();
        ui->le_password->clear();
        ui->le_permissionBits->clear();
        ui->le_role->clear();
        ui->te_roleDescription->clear();
    }
    QWidget::mouseReleaseEvent(event);
    qDebug() << "鼠标松开事件，是否选中数据:" << m_tv_userInfoListSelectflag;
}

void UserManagerMenu::m_on_tv_userInfoList_clicked(const QModelIndex &index)
{
    ui->le_id->setText(m_sqlQueryModel->data(this->m_sqlQueryModel->index(index.row(),0)).toString());
    ui->le_name->setText(m_sqlQueryModel->data(this->m_sqlQueryModel->index(index.row(),1)).toString());
    ui->le_password->setText(m_sqlQueryModel->data(this->m_sqlQueryModel->index(index.row(),2)).toString());
    ui->le_permissionBits->setText(m_sqlQueryModel->data(this->m_sqlQueryModel->index(index.row(),3)).toString());
    ui->le_role->setText(m_sqlQueryModel->data(this->m_sqlQueryModel->index(index.row(),4)).toString());
    ui->te_roleDescription->setText(m_sqlQueryModel->data(this->m_sqlQueryModel->index(index.row(),5)).toString());

    switch(roleMap[ui->le_role->text()])
    {
        case Role::ADMIN: ui->rbtn_roleAdmin->click();break;
        case Role::USER_INFO:ui->rbtn_roleUserInfo->click();break;
        case Role::USER_STORE_IO:ui->rbtn_roleUserStoreIO->click();break;
        case Role::USER_STORE_CHECK:ui->rbtn_roleUserStoreCheck->click();break;
        default:qDebug() << "选中数据的角色枚举数据有误";break;
    }

    m_tv_userInfoListSelectflag = true;
    m_tv_userInfoListSelectUserId = m_sqlQueryModel->data(this->m_sqlQueryModel->index(index.row(),0)).toInt();
    qDebug() << "点击列表，是否选中数据:" << m_tv_userInfoListSelectflag << m_tv_userInfoListSelectUserId;
}

void UserManagerMenu::m_on_btn_add_clicked()
{
    QString hintTitle = "添加用户提示";
    QSqlQuery q;
    m_tv_userInfoListSelectflag=false;

    if(!(m_userInfo.getPermissionBits() & static_cast<qint64>(UPBits::USER_ADMIN_ADD)))
    {
        QMessageBox::information(this,hintTitle,"你没有添加用户信息的权限");
        return;
    }

    if(ui->le_id->text().isEmpty() || ui->le_name->text().isEmpty() || ui->le_password->text().isEmpty())
    {
        QMessageBox::information(this,hintTitle,"用户必要信息缺失(id,姓名,密码,角色类型)");
        return;
    }

    q.prepare("INSERT user VALUES(?,?,?,?,?,?)");
    q.addBindValue(ui->le_id->text().toInt());
    q.addBindValue(ui->le_name->text());
    q.addBindValue(ui->le_password->text());
    q.addBindValue(ui->le_permissionBits->text().toUInt());
    q.addBindValue(ui->le_role->text());
    q.addBindValue(ui->te_roleDescription->toPlainText());

    if(!q.exec())
    {
        QMessageBox::information(this,hintTitle,QString("添加用户语句执行失败: %1").arg(q.lastError().text()));
        return;
    }

    m_sqlQueryModel->setQuery("SELECT * FROM user");
    QMessageBox::information(this,hintTitle,QString("添加%1用户成功").arg(ui->le_name->text()));

    LogManagerMenu::insertLog(QDateTime::currentMSecsSinceEpoch(),
                              QString(m_userInfo.getName()),
                              m_userInfo.getRole(),
                              QString("添加了一个人员信息:[add]%1").arg(ui->le_name->text()));
}

void UserManagerMenu::m_on_btn_delete_clicked()
{
    QString hintTitle = "删除用户提示";
    QSqlQuery q;

    if(!(m_userInfo.getPermissionBits() & static_cast<qint64>(UPBits::USER_ADMIN_DELETE)))
    {
        QMessageBox::information(this,hintTitle,"你没有删除用户信息的权限");
        return;
    }

    if(!m_tv_userInfoListSelectflag)
    {
        QMessageBox::information(this,hintTitle,"点击删除用户按钮之前请先选择一条数据");
        return;
    }
    m_tv_userInfoListSelectflag=false;

    q.prepare("DELETE FROM user WHERE id=?");
    q.addBindValue(m_tv_userInfoListSelectUserId);

    if(!q.exec())
    {
        QMessageBox::information(this,hintTitle,QString("删除用户语句执行失败: %1").arg(q.lastError().text()));
        return;
    }

    m_sqlQueryModel->setQuery("SELECT * FROM user");
    QMessageBox::information(this,hintTitle,"删除成功");

    LogManagerMenu::insertLog(QDateTime::currentMSecsSinceEpoch(),
                              QString(m_userInfo.getName()),
                              m_userInfo.getRole(),
                              QString("删除了一个人员信息:[delete]%1").arg(ui->le_name->text()));
}

void UserManagerMenu::m_on_btn_update_clicked()
{
    QString hintTitle = "修改用户提示";
    QSqlQuery q;

    if(!(m_userInfo.getPermissionBits() & static_cast<qint64>(UPBits::USER_ADMIN_MODIFY)))
    {
        QMessageBox::information(this,hintTitle,"你没有修改用户信息的权限");
        return;
    }

    if(!m_tv_userInfoListSelectflag)
    {
         QMessageBox::information(this,hintTitle,"点击修改用户按钮之前请先选择一条数据");
        return;
    }
    m_tv_userInfoListSelectflag=false;

    if(ui->le_id->text().isEmpty() || ui->le_name->text().isEmpty() || ui->le_password->text().isEmpty())
    {
        QMessageBox::information(this,hintTitle,"修改用户必要信息缺失(id,姓名,密码,角色类型)");
        return;
    }

    q.prepare("UPDATE user SET id=?,name=?,password=?,permissionBits=?,role=?,roleDescription=? WHERE id=?");
    q.addBindValue(ui->le_id->text().toInt());
    q.addBindValue(ui->le_name->text());
    q.addBindValue(ui->le_password->text());
    q.addBindValue(ui->le_permissionBits->text().toUInt());
    q.addBindValue(ui->le_role->text());
    q.addBindValue(ui->te_roleDescription->toPlainText());

    q.addBindValue(m_tv_userInfoListSelectUserId);

    if(!q.exec())
    {
        QMessageBox::information(this,hintTitle,QString("修改用户语句执行失败: %1").arg(q.lastError().text()));
        return;
    }

    m_sqlQueryModel->setQuery("SELECT * FROM user");

    LogManagerMenu::insertLog(QDateTime::currentMSecsSinceEpoch(),
                              QString(m_userInfo.getName()),
                              m_userInfo.getRole(),
                              QString("修改了一个人员信息:[update]%1").arg(ui->le_name->text()));
}

void UserManagerMenu::m_on_btn_find_clicked()
{
    QString hintTitle = "查询用户提示";

    if(!(m_userInfo.getPermissionBits() & static_cast<qint64>(UPBits::USER_ADMIN_FIND)))
    {
        QMessageBox::information(this,hintTitle,"你没有查找用户信息的权限");
        return;
    }

    if(ui->le_find->text().isEmpty())
    {
        QMessageBox::information(this,hintTitle,"请输入要查询用户的姓名，支持模糊查询");
    }

    QString safeInput = ui->le_find->text()
                            .replace("'", "''")   // 转义单引号
                            .replace("%", "\\%")  // 转义LIKE通配符
                            .replace("_", "\\_"); // 转义LIKE通配符
    QString q = QString("SELECT * FROM user WHERE name LIKE '%%1%'").arg(safeInput);

    qDebug() << q;

    m_sqlQueryModel->setQuery(q);

    if(m_sqlQueryModel->lastError().isValid())
    {
        QMessageBox::warning(this, hintTitle, m_sqlQueryModel->lastError().text());
    }

    LogManagerMenu::insertLog(QDateTime::currentMSecsSinceEpoch(),
                              QString(m_userInfo.getName()),
                              m_userInfo.getRole(),
                              QString("查询了人员信息:[find]%1").arg(ui->le_find->text()));
}

void UserManagerMenu::m_on_tbtn_permissionBitsChose_clicked()
{
    PB_t tmpPB = ui->le_permissionBits->text().toUInt();
    PermissionBitsChoseMenu* tmpPermissionBitsChoseMenu = new PermissionBitsChoseMenu(roleMap[ui->le_role->text()],tmpPB,this);
    tmpPermissionBitsChoseMenu->setAttribute(Qt::WA_DeleteOnClose);//关闭自动线销毁
    connect(tmpPermissionBitsChoseMenu,&PermissionBitsChoseMenu::dataConfirmed,this,[=](PB_t pb)mutable
    {
        ui->le_permissionBits->setText(QString("%1").arg(pb));
    });
    tmpPermissionBitsChoseMenu->exec();
}

